<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { ArrowLeft, Upload } from "@element-plus/icons-vue";
import { updateUserInfo, updateAvatar, changePassword } from "@/api/user";

const router = useRouter();
const store = useStore();

// 用户信息表单
const userForm = ref({
    username: "",
    nickname: "",
    email: "",
    phone: "",
    gender: "",
    birth_date: "",
    address: "",
    introduction: "",
    avatar: "",
});

// 密码表单
const passwordForm = ref({
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
});

// 表单校验规则
const rules = reactive({
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
    ],
    email: [
        { required: false, message: "请输入邮箱地址", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    ],
    phone: [
        { required: false, message: "请输入手机号", trigger: "blur" },
        { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
    ],
});

const passwordRules = reactive({
    oldPassword: [
        { required: true, message: "请输入原密码", trigger: "blur" },
        { min: 6, message: "密码至少6个字符", trigger: "blur" },
    ],
    newPassword: [
        { required: true, message: "请输入新密码", trigger: "blur" },
        { min: 6, message: "密码至少6个字符", trigger: "blur" },
    ],
    confirmPassword: [
        { required: true, message: "请再次输入新密码", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                if (value !== passwordForm.value.newPassword) {
                    callback(new Error("两次输入的密码不一致"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
});

// 表单引用
const userFormRef = ref();
const passwordFormRef = ref();

// 标签页激活名称
const activeTab = ref("userInfo");

// 表单加载状态
const loading = ref(false);
const passwordLoading = ref(false);

// 头像上传相关
const avatarUrl = computed(
    () => userForm.value.avatar || "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);
const avatarUploading = ref(false);

// 头像上传前检查
const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith("image/");
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error("头像必须是图片文件!");
        return false;
    }
    if (!isLt2M) {
        ElMessage.error("头像大小不能超过 2MB!");
        return false;
    }
    return true;
};

// 头像上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
    avatarUploading.value = false;
    if (response.code === 200 || response.code === 0) {
        userForm.value.avatar = response.data.url;
        ElMessage.success("头像上传成功");
    } else {
        ElMessage.error("头像上传失败");
    }
};

// 头像上传失败回调
const handleAvatarError = () => {
    avatarUploading.value = false;
    ElMessage.error("头像上传失败");
};

// 获取用户信息
const getUserInfo = async () => {
    try {
        await store.dispatch("user/getUserInfo");
        const userInfo = store.state.user.userInfo;

        // 填充表单数据
        userForm.value = {
            username: userInfo.user_name || userInfo.account || "",
            nickname: userInfo.nickname || "",
            email: userInfo.email || "",
            phone: userInfo.phone || "",
            gender: userInfo.gender || "",
            birth_date: userInfo.birth_date || "",
            address: userInfo.address || "",
            introduction: userInfo.introduction || "",
            avatar: userInfo.avatar || "",
        };
    } catch (error) {
        console.error("获取用户信息失败", error);
        ElMessage.error("获取用户信息失败");
    }
};

// 提交用户信息
const submitUserInfo = async () => {
    if (!userFormRef.value) return;

    try {
        await userFormRef.value.validate();
        loading.value = true;

        const response = await updateUserInfo(userForm.value);
        if (response.code === 200 || response.code === 0) {
            // 更新本地用户信息
            store.commit("user/SET_USER_INFO", {
                ...store.state.user.userInfo,
                user_name: userForm.value.username,
                nickname: userForm.value.nickname,
                email: userForm.value.email,
                phone: userForm.value.phone,
                gender: userForm.value.gender,
                birth_date: userForm.value.birth_date,
                address: userForm.value.address,
                introduction: userForm.value.introduction,
                avatar: userForm.value.avatar,
            });

            ElMessage.success("个人信息更新成功");
        } else {
            ElMessage.error("个人信息更新失败");
        }
    } catch (error) {
        console.error("提交个人信息失败", error);
        ElMessage.error("表单验证失败或提交过程中出错");
    } finally {
        loading.value = false;
    }
};

// 提交密码修改
const submitPasswordChange = async () => {
    if (!passwordFormRef.value) return;

    try {
        await passwordFormRef.value.validate();
        passwordLoading.value = true;

        const response = await changePassword({
            oldPassword: passwordForm.value.oldPassword,
            newPassword: passwordForm.value.newPassword,
        });

        if (response.code === 200 || response.code === 0) {
            ElMessage.success("密码修改成功");
            // 清空表单
            passwordForm.value = {
                oldPassword: "",
                newPassword: "",
                confirmPassword: "",
            };
            // 切换回用户信息标签页
            activeTab.value = "userInfo";
        } else {
            ElMessage.error(response.message || "密码修改失败");
        }
    } catch (error) {
        console.error("提交密码修改失败", error);
        ElMessage.error("表单验证失败或提交过程中出错");
    } finally {
        passwordLoading.value = false;
    }
};

// 返回上一页
const goBack = () => {
    router.go(-1);
};

onMounted(() => {
    getUserInfo();
});
</script>

<template>
    <div class="user-info-container">
        <div class="page-header">
            <el-button link @click="goBack" :icon="ArrowLeft">返回</el-button>
            <h2>个人资料</h2>
        </div>

        <el-tabs v-model="activeTab" class="user-info-tabs">
            <el-tab-pane label="基本信息" name="userInfo">
                <el-form
                    ref="userFormRef"
                    :model="userForm"
                    :rules="rules"
                    label-width="100px"
                    label-position="left"
                    class="user-form"
                    v-loading="loading"
                >
                    <div class="avatar-container">
                        <div class="avatar-uploader">
                            <el-upload
                                class="avatar-uploader"
                                action="/api/user/avatar"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :on-error="handleAvatarError"
                                :before-upload="beforeAvatarUpload"
                            >
                                <el-avatar
                                    :size="100"
                                    :src="avatarUrl"
                                    v-if="avatarUrl && !avatarUploading"
                                ></el-avatar>
                                <el-icon v-else-if="avatarUploading" class="avatar-uploader-icon"><Loading /></el-icon>
                                <div class="avatar-upload-mask" v-if="!avatarUploading">
                                    <el-icon><Upload /></el-icon>
                                    <span>上传头像</span>
                                </div>
                            </el-upload>
                        </div>
                        <div class="avatar-tip">
                            <p>建议使用正方形头像</p>
                            <p>文件大小不超过 2MB</p>
                        </div>
                    </div>

                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userForm.username" />
                    </el-form-item>

                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="userForm.nickname" />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" type="email" />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" />
                    </el-form-item>

                    <el-form-item label="性别">
                        <el-radio-group v-model="userForm.gender">
                            <el-radio label="male">男</el-radio>
                            <el-radio label="female">女</el-radio>
                            <el-radio label="other">其他</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="生日">
                        <el-date-picker
                            v-model="userForm.birth_date"
                            type="date"
                            placeholder="选择生日"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>

                    <el-form-item label="所在地">
                        <el-input v-model="userForm.address" />
                    </el-form-item>

                    <el-form-item label="个人简介">
                        <el-input
                            v-model="userForm.introduction"
                            type="textarea"
                            :rows="4"
                            placeholder="介绍一下自己吧"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submitUserInfo" :loading="loading">保存信息</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
                <el-form
                    ref="passwordFormRef"
                    :model="passwordForm"
                    :rules="passwordRules"
                    label-width="100px"
                    class="password-form"
                    v-loading="passwordLoading"
                >
                    <el-form-item label="原密码" prop="oldPassword">
                        <el-input
                            v-model="passwordForm.oldPassword"
                            type="password"
                            placeholder="请输入当前密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                        <el-input
                            v-model="passwordForm.newPassword"
                            type="password"
                            placeholder="请输入新密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input
                            v-model="passwordForm.confirmPassword"
                            type="password"
                            placeholder="请再次输入新密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submitPasswordChange" :loading="passwordLoading"
                            >修改密码</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<style scoped>
.user-info-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin-left: 10px;
    margin-bottom: 0;
}

.user-form,
.password-form {
    max-width: 600px;
}

.avatar-container {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
}

.avatar-uploader {
    position: relative;
    cursor: pointer;
    overflow: hidden;
}

.avatar-uploader .el-avatar {
    display: block;
}

.avatar-upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 14px;
    opacity: 0;
    transition: opacity 0.3s;
    border-radius: 50%;
}

.avatar-uploader:hover .avatar-upload-mask {
    opacity: 1;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar-tip {
    margin-left: 20px;
    color: #666;
    font-size: 12px;
    line-height: 1.6;
}

@media screen and (max-width: 768px) {
    .avatar-container {
        flex-direction: column;
        align-items: center;
    }

    .avatar-tip {
        margin-left: 0;
        margin-top: 10px;
        text-align: center;
    }
}
</style>
